//
//  SEGCommentInputView.m
//  SEGUhomeSommunitySocial
//
//  Created by 揭婧雯 on 2018/12/3.
//  Copyright © 2018 刘山. All rights reserved.
//

#import "SEGCommentInputView.h"
#import <SEGPlatform/SEGAdDisplayManager.h>
#import "SEGBasicBussinessCommonDefine.h"
#import "SEGAlertView.h"

@implementation SEGCommentInputView
- (instancetype)init
{
    NSLog(@"%s",__FUNCTION__);
    self = [super init];
    if (self) {
        [self setUpUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    NSLog(@"%s",__FUNCTION__);
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpUI];
    }
    return self;
}

- (void)setUpUI
{
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    
    // inputBarView:弹出键盘后 键盘上方的输入视图
    self.alpha = 0;
    self.frame = [UIScreen mainScreen].bounds;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchCommentInputViewAction:)];
    [self addGestureRecognizer:tap];
    
    [self addSubview:self.inputBarView];
    [self hiddenCommentInputView];
    
    [self.inputBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.equalTo(self.mas_bottom).offset(KSEGInputBarViewHeight + LYScreenWidth()/6.4);
        make.height.mas_greaterThanOrEqualTo(KSEGInputBarViewHeight);
    }];
    
    [self segInitNotification];
}

- (void)touchCommentInputViewAction:(UITapGestureRecognizer *)tap
{
    CGPoint point = [tap locationInView:self];
    BOOL isInputBarView = CGRectContainsPoint(self.inputBarView.frame, point);
    if (!isInputBarView) {
        [self hiddenCommentInputView];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(afterTouchCommentInputView)]) {
        [self.delegate afterTouchCommentInputView];
    }
}



- (void)segInitNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideChangeFrame:) name:UIKeyboardWillHideNotification object:nil];
}

// 显示广告
-(void)segShowTencentAD
{
    NSLog(@"%s placementId:%@",__FUNCTION__,self.GDTPosId);
    [self segHiddenTencentAD];
    
    if ([self.GDTPosId isEqualToString:KGDTPosIdNeighbourListCommentID]) {//邻里圈评论    邻里圈评论输入框
        if(![[SEGAdDisplayManager shared] getAdWhetherShow:SEGAD_NeighborCommentType]) return;
    }else if ([self.GDTPosId isEqualToString:KGDTPosIdNeighbourDetailCommentID]) {//帖子详情页评论    用户帖子详情页的输入框
        if(![[SEGAdDisplayManager shared] getAdWhetherShow:SEGAD_NeighborDetailCommentType]) return;
    }else if ([self.GDTPosId isEqualToString:KGDTPosIdPGCDetailCommentID]) {//日报评论    日报评论输入框
        if(![[SEGAdDisplayManager shared] getAdWhetherShow:SEGAD_PGCDetailCommentType]) return;
    }else if ([self.GDTPosId isEqualToString:KGDTPosIdTextTopicCommentID]) { //文字话题回复    文字话题回复输入框
        if(![[SEGAdDisplayManager shared] getAdWhetherShow:SEGAD_WordTopicCommentType]) return;
    }
    
    //if (!self.bannerAdView) {
    //self.bannerAdView = [[GDTUnifiedBannerView alloc] initWithFrame:CGRectZero appId:kGDTAppkey placementId:self.GDTPosId viewController:self.currentViewController];
    self.bannerAdView = [[GDTUnifiedBannerView alloc] initWithFrame:CGRectZero placementId:self.GDTPosId viewController:self.currentViewController];
    self.bannerAdView.accessibilityIdentifier = @"banner_ad";
    self.bannerAdView.autoSwitchInterval = 30;
    self.bannerAdView.delegate = self;
    
    self.bannerAdView.backgroundColor = [UIColor clearColor];
    self.bannerAdView.clipsToBounds = YES;
    self.bannerAdView.userInteractionEnabled = YES;
    [self.bannerAdView loadAdAndShow];
    [self addSubview:self.bannerAdView];
    
    [self.bannerAdView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.height.mas_equalTo(LYScreenWidth()/6.4);
        make.bottom.equalTo(self.inputBarView.mas_top);
    }];
    //}
}

// 隐藏广告
-(void)segHiddenTencentAD
{
    NSLog(@"%s",__FUNCTION__);
    if (self.bannerAdView) {
        [self.bannerAdView removeFromSuperview];
        self.bannerAdView = nil;
    }
}

- (void)showCommentInputView {
    NSLog(@"%s",__FUNCTION__);
    // !!!:  Wendy，2019-1-14, 解决长按广告栏取消后，键盘无法再次弹出问题
    /*
     参考文章http://th7.cn/Program/IOS/201701/1076183.shtml的思路
     猜想:[alert show]的时候会有一个蒙层,苹果为了保证美观性,暂时强制隐藏键盘,从而导致resignFirstResponder 的键盘消失动画延迟,当点击alertView上边的"取消"和"确定"之后处理了键盘消失动画.
     换一种说法就是:当runLoop接收到UITextField结束第一响应者的消息后,放在了调用队列中,不会马上执行键盘收起,这个时候又接收到了[alert show]的消息,系统会优先处理[alert show]的消息,挂起[UITextField resignFirstResponder];当处理完alertView的时候,再继续执行resignFirstResponder的键盘动画;
     也就是长安后并没有成功注销第一响应者，也就导致becomeFirstResponder不起任何作用，因此要先判断是否为第一响应者，如果是先注销第一响应者
     */
    if ([self.inputBarView.textView isFirstResponder]) {
        [self.inputBarView.textView resignFirstResponder];
    }
    
    [self.inputBarView.textView becomeFirstResponder];
}

- (void)hiddenCommentInputView {
    NSLog(@"%s",__FUNCTION__);
    [self.inputBarView.textView resignFirstResponder];
    self.inputBarView.textView.text = @"";
}

- (void)removeFromSuperview
{
    NSLog(@"%s",__FUNCTION__);
    [super removeFromSuperview];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    self.currentViewController = nil;
    
    self.bannerAdView.delegate = nil;
    //self.bannerAdView.currentViewController = nil;
    [self.bannerAdView removeFromSuperview];
    self.bannerAdView = nil;
}

#pragma mark - 腾讯广告 & GDTMobBannerViewDelegate
// 请求广告条数据成功
- (void)bannerViewDidReceived {
    NSLog(@"请求广告条数据成功后调用 详解:当接收服务器返回的广告数据成功后调用该函数 %s",__FUNCTION__);
}

// 请求广告条数据失败
- (void)bannerViewFailToReceived:(NSError *)error {
    NSLog(@"请求广告条数据失败后调用 %s",__FUNCTION__);
    if(![[[NSUserDefaults standardUserDefaults] valueForKey:kUserDefaultIsProduction] boolValue]){[SEGAlertView showTmepMessageWithMessage:error.localizedDescription];}
}

// 应用进入后台
- (void)bannerViewWillLeaveApplication {
}

- (void)bannerViewWillClose {
    self.bannerAdView.alpha = 0;
}

/**
 *  banner条点击回调
 */
- (void)bannerViewClicked
{
//    [self hiddenCommentInputView];
}

#pragma mark - GDTUnifiedBannerViewDelegate
- (void)unifiedBannerViewDidLoad:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"请求广告条数据成功后调用,当接收服务器返回的广告数据成功后调用该函数%s frame:%@",__FUNCTION__,NSStringFromCGRect(unifiedBannerView.frame));
}
- (void)unifiedBannerViewFailedToLoad:(GDTUnifiedBannerView *)unifiedBannerView error:(NSError *)error{
    if(![[[NSUserDefaults standardUserDefaults] valueForKey:kUserDefaultIsProduction] boolValue]){[SEGAlertView showTmepMessageWithMessage:error.localizedDescription];}
    NSLog(@"请求广告条数据失败后调用,当接收服务器返回的广告数据失败后调用该函数%s errMsg:%@ errCode:%zd",__FUNCTION__,error.localizedDescription,error.code);
}
- (void)unifiedBannerViewWillExpose:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"banner2.0曝光回调%s",__FUNCTION__);
}
- (void)unifiedBannerViewClicked:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"banner2.0点击回调%s",__FUNCTION__);
}
- (void)unifiedBannerViewWillPresentFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"banner2.0广告点击以后即将弹出全屏广告页%s",__FUNCTION__);
}
- (void)unifiedBannerViewDidPresentFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"banner2.0广告点击以后弹出全屏广告页完毕%s",__FUNCTION__);
}
- (void)unifiedBannerViewWillDismissFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"全屏广告页即将被关闭%s",__FUNCTION__);
}
- (void)unifiedBannerViewDidDismissFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"全屏广告页已经被关闭%s",__FUNCTION__);
}
- (void)unifiedBannerViewWillLeaveApplication:(GDTUnifiedBannerView *)unifiedBannerView{
    NSLog(@"当点击应用下载或者广告调用系统程序打开%s",__FUNCTION__);
}
- (void)unifiedBannerViewWillClose:(GDTUnifiedBannerView *)unifiedBannerView{
    //self.bannerView = nil;
    self.bannerAdView.alpha = 0;
    NSLog(@"banner2.0被用户关闭时调用%s",__FUNCTION__);
}


#pragma mark - action

- (void)seg_sendButtonPressed:(UIButton *)sender {
//    NSInteger len = self.inputBarView.textView.text.length;
//    if ([[self.inputBarView.textView.text segFilterEmoji] length] != len) {
//        //        [self.inputBarView.textView resignFirstResponder];
//        [SEGAlertView showTmepMessageWithMessage:@"暂不支持表情，请重新输入"];
//        return;
//    }
    if ([self.delegate respondsToSelector:@selector(sendButtonActionWithContent:)]) {
        [self.delegate sendButtonActionWithContent:self.inputBarView.textView.text];
    }
}


#pragma mark - 键盘弹出

- (void)keyboardWillShowChangeFrame:(NSNotification*)notification {
    if (![self.inputBarView.textView isFirstResponder]) {
        return;
    }
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    [self.inputBarView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottom).offset(-kbSize.height);
    }];
    
    //    [self.layer removeAllAnimations];
    
    [UIView animateWithDuration:duration animations:^{
        self.alpha = 1;
        [self layoutIfNeeded];
    } completion:nil];
}

- (void)keyboardWillHideChangeFrame:(NSNotification*)notification {
    NSDictionary* info = [notification userInfo];
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [self.inputBarView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottom).offset(KSEGInputBarViewHeight + CGSizeMake(320, 50).height);
    }];
    
    [UIView animateWithDuration:duration animations:^{
        [self layoutIfNeeded];
        self.alpha = 0;
    }];
}

#pragma mark - getter
- (SEGInputBarView *)inputBarView {
    if (!_inputBarView) {
        _inputBarView = [[SEGInputBarView alloc] init];
        [_inputBarView.sendButton addTarget:self action:@selector(seg_sendButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _inputBarView;
}

- (void)setPlaceholderText:(NSString *)placeholderText
{
    if(placeholderText.length > 0) {
        self.inputBarView.placeholderText = placeholderText;
    }
}

@end
